using UnityEngine;

public class					entity_unit : entity
{
	public enum					e_team	{
		red,
		green
	};
	
	private enum				e_state {
		initial,
		idle,
		walk,
		attack,
		zombie
	};
	
	public float				speed;
	public float				hps;

	private float				dx;
	private float				sx;
	private e_team				team;
	private e_state				current_state;
	private int					target;

	public override void		init() 
	{
		add_anim_end_event		("death");
		switch_state			(e_state.walk);
	}
	
	public override void		trigger_enter	(Collider other)
	{
		target					= e_server.instance.find( other.GetComponent<entity>().GetInstanceID() ).GetInstanceID();
		switch_state			(e_state.attack);
	}
	
	public override void		trigger_exit	(Collider other)
	{
Debug.Log(other.ToString());
	}

	public override void		update			(float dt_s) {
		update_input			();
		update_state			();
	}

	public override void        zombie			()
	{
		Debug.Log("zombie");
		switch_state			(e_state.zombie);
	}

	private void				switch_state	(e_state state) {
		switch (state)	{
		case e_state.idle:
		{
			switch (current_state)	{
				case e_state.initial:
				case e_state.walk:
				case e_state.attack:			on_idle();	break;
			}
		}
		break;
		case e_state.walk:
		{
			switch (current_state)	{
			case e_state.initial:
			case e_state.idle:							
			case e_state.attack:				on_walk();	break;
			}
		}
		break;
		case e_state.attack:
		{
			switch (current_state)	{
			case e_state.initial:
			case e_state.idle:
			case e_state.walk:					on_attack(); break;
			}
		}	
		break;
		case e_state.zombie:					on_zombie(); break;	
		default:
			Debug.Break();	
			break;
		}		
		
		current_state = state;
	}
	
	private void update_input() {
		if (Input.GetButtonDown("Fire1"))		switch_state(e_state.zombie);
	}

	private void update_state()	{
		if (current_state == e_state.attack) {
			entity e		= e_server.instance.find(target);
			if (e)
			    e.damage	(hps * Time.deltaTime);
			else
			    switch_state(e_state.idle);
		}
	}
	
	private void on_idle() {
		Debug.Log("on_idle");
 		animation.CrossFade("idle");
		sx = 0.0f;
	}
	
	private void on_walk() {
		animation.CrossFade("walk");
		sx = 1.0f;
	}
	
	private void on_attack() {
		animation.CrossFade("attack_01");
		sx = 0.0f;
	}
	
	private void on_zombie() {
		Debug.Log("on_zombie");
		animation.CrossFade("death");
		sx = 0.0f;
	}
	
	/// <summary>
	/// animation events
	/// </summary>
	void death_anim_end(AnimationEvent ev)
	{
		Debug.Log(ev);
		die();
	}

	/// <summary>
	/// accessors
	/// </summary>
	public float Dx {
		get {
			return this.dx;
		}
		set {
			dx = value;
			Vector3 scale = transform.localScale;
			scale.x = -dx;
			transform.localScale = scale;
		}
	}
	
	public float Sx {
		get {
			return this.sx;
		}
	}
	
	public e_team Team {
		get {
			return this.team;
		}
		set {
			team = value;
		}
	}

}
